package com.yunji.web.system;

import com.google.common.collect.Maps;
import com.yunji.base.cache.BaseCache;
import com.yunji.common.annotation.Log;
import com.yunji.common.base.BaseController;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.enums.common.BusinessType;
import com.yunji.common.model.domain.SysDeptDO;
import com.yunji.common.model.domain.SysRoleDO;
import com.yunji.common.model.domain.SysUserDO;
import com.yunji.common.model.domain.SysUserRoleDO;
import com.yunji.common.model.dto.LoginInfo;
import com.yunji.common.utils.ExcelUtil;
import com.yunji.common.utils.StringUtils;
import com.yunji.system.context.SystemContext;
import com.yunji.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@Api(tags = "角色信息")
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @ApiOperation("角色列表")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public Response<List<SysRoleDO>> list(SysRoleDO role) {
        List<SysRoleDO> list = roleService.selectRoleList(role);
        return ResponseHelper.successWithPage(list);
    }

    @ApiOperation("角色导出")
    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRoleDO role) {
        List<SysRoleDO> list = roleService.selectRoleList(role);
        ExcelUtil<SysRoleDO> util = new ExcelUtil<>(SysRoleDO.class);
        util.exportExcel(response, list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @ApiOperation("根据角色编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public Response<SysRoleDO> getInfo(@PathVariable Long roleId) {
        return ResponseHelper.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @ApiOperation("新增角色")
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Response<Long> add(@Validated @RequestBody SysRoleDO role) {
        if (!roleService.checkRoleNameUnique(role)) {
            return ResponseHelper.failure("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return ResponseHelper.failure("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SystemContext.getUsername());
        Assert.isTrue(roleService.insertRole(role) > 0, "新增失败");
        return ResponseHelper.success(role.getRoleId());

    }

    /**
     * 修改保存角色
     */
    @ApiOperation("修改保存角色")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Response<String> edit(@Validated @RequestBody SysRoleDO role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(role)) {
            return ResponseHelper.failure("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return ResponseHelper.failure("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SystemContext.getUsername());

        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            LoginInfo loginUser = SystemContext.getUser();
            if (StringUtils.isNotNull(loginUser) && !loginUser.isAdmin()) {
                loginUser.setPermissions(permissionService.getMenuPermission(BaseCache.getUser(loginUser.getUserId())));
                tokenService.setLoginUser(loginUser);
            }
            return ResponseHelper.success();
        }
        return ResponseHelper.failure("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @ApiOperation("修改保存数据权限")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public Response<String> dataScope(@RequestBody SysRoleDO role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        Assert.isTrue(roleService.authDataScope(role) > 0, "修改失败");
        return ResponseHelper.success();
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public Response<String> changeStatus(@RequestBody SysRoleDO role) {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SystemContext.getUsername());
        Assert.isTrue(roleService.updateRoleStatus(role) > 0, "修改失败");
        return ResponseHelper.success();
    }

    /**
     * 删除角色
     */
    @ApiOperation("删除角色")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public Response<String> remove(@PathVariable Long[] roleIds) {
        Assert.isTrue(roleService.deleteRoleByIds(roleIds) > 0, "删除失败");
        return ResponseHelper.success();
    }

    /**
     * 获取角色选择框列表
     */
    @ApiOperation("获取角色选择框列表")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public Response<List<SysRoleDO>> optionselect() {
        return ResponseHelper.success(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */
    @ApiOperation("查询已分配用户角色列表")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/allocatedList")
    public Response<List<SysUserDO>> allocatedList(SysUserDO user) {
        List<SysUserDO> list = userService.selectAllocatedList(user);
        return ResponseHelper.successWithPage(list);
    }

    /**
     * 查询未分配用户角色列表
     */
    @ApiOperation("查询未分配用户角色列表")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/unallocatedList")
    public Response<List<SysUserDO>> unallocatedList(SysUserDO user) {
        List<SysUserDO> list = userService.selectUnallocatedList(user);
        return ResponseHelper.successWithPage(list);
    }

    /**
     * 取消授权用户
     */
    @ApiOperation("取消授权用户")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public Response<String> cancelAuthUser(@RequestBody SysUserRoleDO userRole) {
        Assert.isTrue(roleService.deleteAuthUser(userRole) > 0, "取消失败");
        return ResponseHelper.success();
    }

    /**
     * 批量取消授权用户
     */
    @ApiOperation("批量取消授权用户")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public Response<String> cancelAuthUserAll(Long roleId, Long[] userIds) {
        Assert.isTrue(roleService.deleteAuthUsers(roleId, userIds) > 0, "取消失败");
        return ResponseHelper.success();
    }

    /**
     * 批量选择用户授权
     */
    @ApiOperation("批量选择用户授权")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public Response<String> selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        Assert.isTrue(roleService.insertAuthUsers(roleId, userIds) > 0, "授权失败");
        return ResponseHelper.success();
    }

    /**
     * 获取对应角色部门树列表
     */
    @ApiOperation("获取对应角色部门树列表")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/deptTree/{roleId}")
    public Response<Map<String, Object>> deptTree(@PathVariable("roleId") Long roleId) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        map.put("depts", deptService.selectDeptTreeList(new SysDeptDO()));
        return ResponseHelper.success(map);
    }
}
